package gr.uoa.di.thanos.botcraft.server;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.ServerSocket;
import java.net.URL;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.logging.Level;
import java.util.logging.Logger;

import gr.uoa.di.thanos.botcraft.game.Game;

public class Server implements Runnable {
	private static final Logger logger = Logger.getLogger(Server.class.getName());
	
	private final int port;
	private final URL gameUrl;
	
	public static void main(final String[] arguments) {
		if (arguments.length < 2) {
			System.err.println("Usage: java " + Server.class.getName() + " <port> <game>");
			return;
		}
		try {
			new Server(Integer.parseInt(arguments[0]), new URL(arguments[1])).run();
		} catch (NumberFormatException e) {
			logger.log(Level.SEVERE, "Invalid port " + arguments[0]);
		} catch (MalformedURLException e) {
			logger.log(Level.SEVERE, "Invalid game URL: " + arguments[1]);
		}
	}
	
	public Server(final int port, final URL gameUrl) {
		this.port = port;
		this.gameUrl = gameUrl;
	}
	
	@Override
	@SuppressWarnings("unchecked")
	public void run() {
//		try {
			final Game game = null;
			final BlockingQueue<String> inputQueue = new LinkedBlockingQueue<String>();
//			final BlockingQueue<String>[] outputQueues = new BlockingQueue[game.getPlayers().size()];
//			final Thread[] workers = new Thread[game.getPlayers().size()];
//			final Thread dispatcher = new Thread(new Dispatcher(inputQueue, outputQueues));
			try {
				final ServerSocket socket = new ServerSocket(port);
				logger.info("Listening on port " + port);
//				dispatcher.start();
//				for (int i = 0; (i < workers.length) && (!Thread.interrupted()); i++) {
//					try {
//						outputQueues[i] = new LinkedBlockingQueue<String>();
////						workers[i] = new Thread(new ThreadGroup(Worker.class.getName() + " " + i), new Worker(socket.accept(), inputQueue, outputQueues[i]));
//						workers[i].start();
//					} catch (IOException e) {
//						logger.log(Level.WARNING, "Error accepting connection", e);
//						i--;
//					}
//					try {
//						socket.close();
//					} catch (IOException e) {
//						logger.log(Level.WARNING, "Error closing port " + port, e);
//					}
//					try {
//						for (Thread worker : workers)
//							worker.join();
//					} catch (InterruptedException e) {
//						return;
//					} finally {
//						dispatcher.interrupt();
//					}
//				}	
			} catch (IOException e) {
				logger.log(Level.SEVERE, "Error listening on port " + port);
			}
//		} catch (ClassNotFoundException e) {
//			logger.log(Level.SEVERE, "Error loading game " + gameUrl, e);
//		} catch (IOException e) {
//			logger.log(Level.SEVERE, "Error loading game " + gameUrl, e);
//		}
	}
}